﻿using Coldairarrow.Business.Base_AutoReplys;
using Coldairarrow.Entity.Base_AutoReplys;
using Coldairarrow.Util;
using Elasticsearch.Service;
using Microsoft.AspNetCore.Mvc;
using Nest;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.Base_AutoReplys
{
    [Route("/Base_AutoReplys/[controller]/[action]")]
    public class Base_AutoReplyController : BaseApiController
    {
        #region DI
        private readonly ElasticClient _client;
        static string IFName = "qlautoreply";
        public Base_AutoReplyController(IBase_AutoReplyBusiness base_AutoReplyBus,IEsClientProvider clientProvider)
        {
            _base_AutoReplyBus = base_AutoReplyBus;
            _client = clientProvider.GetClient();
        }

        IBase_AutoReplyBusiness _base_AutoReplyBus { get; }

        #endregion

        #region 获取

        [HttpPost]
        public async Task<PageResult<Base_AutoReply>> GetDataList(PageInput<GetTSearchDTO> input)
        {
            return await _base_AutoReplyBus.GetDataListAsync(input);
        }

        /// <summary>
        /// 后台——获取自动回复详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Base_AutoReply> GetTheModel(IdInputDTO input)
        {
            return await _base_AutoReplyBus.GetTheModelAsync(input.Id);
        }

        [HttpPost]
        public async Task<Base_AutoReply> GetTheData(IdInputDTO input)
        {
            return await _base_AutoReplyBus.GetTheDataAsync(input.Id);
        }

        #endregion

        #region 提交

        [HttpPost]
        public async Task SaveData(Base_AutoReply data)
        {
            data.Deleted = false;

            //创建索引
            dynamic response = _client.Indices.Get(IFName);
            if (!response.IsValid)
            {
                response = _client.Indices.Create(IFName, c => c
                .Map<Base_AutoReply>(m => m
                    .AutoMap()
                ));
            }

            if (data.Id.IsNullOrEmpty())
            {
                InitEntity(data);

                await _base_AutoReplyBus.AddDataAsync(data);

                //插入文档
                _client.Index(data, i => i.Index(IFName).Id(data.Id));
            }
            else
            {
                await _base_AutoReplyBus.UpdateDataAsync(data);

                //更新文档
                _client.Index(data, i => i.Index(IFName).Id(data.Id));
            }
        }

        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _base_AutoReplyBus.DeleteDataAsync(ids);

            //删除文档
            foreach (var id in ids)
            {
                _client.Delete<Base_AutoReply>(id, d => d.Index(IFName));
            }
        }

        #endregion
    }
}